package com.example.service.config;


import com.example.common.config.AppConfig;
import com.example.common.enums.ImUrlRouteWayEnum;
import com.example.common.enums.RouteHashMethodEnum;
import com.example.common.route.RouteHandle;
import com.example.common.route.algorithm.consistenthash.AbstractConsistentHash;
import com.example.common.route.algorithm.consistenthash.ConsistentHashHandle;
import com.example.common.route.algorithm.consistenthash.TreeMapConsistentHash;
import com.example.common.route.algorithm.loop.LoopHandle;
import com.example.common.route.algorithm.random.RandomHandle;
import com.example.service.utils.SnowflakeIdWorker;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Configuration
public class BeanConfig {


    @Autowired
    AppConfig appConfig;


    @Bean
    public ZkClient buildZKClient(){
        ZkClient zkClient = new ZkClient(appConfig.getZkAddr(),appConfig.getZkConnectTimeOut());
        return zkClient;
    }


    @Bean
    public RouteHandle routeHandle() throws Exception {    //这里是进行选择是是那种机制
//        return new RandomHandle();    //使用随机
//        return new LoopHandle();        //使用轮询
//         ConsistentHashHandle consistentHashHandle= new ConsistentHashHandle();
//        TreeMapConsistentHash treeMapConsistentHash = new TreeMapConsistentHash();
//        consistentHashHandle.setHash(treeMapConsistentHash);

        Integer imRouteWay = appConfig.getImRouteWay();
        ImUrlRouteWayEnum handler = ImUrlRouteWayEnum.getHandler(imRouteWay);
        String routeway= handler.getClazz();   //获取到全路径名
        RouteHandle routeHandle = (RouteHandle) Class.forName(routeway).newInstance();    //通过反射进行实现
        if(handler==ImUrlRouteWayEnum.HASH){
            Method setHash = Class.forName(routeway).getMethod("setHash", AbstractConsistentHash.class);
            Integer consistentHashWay = appConfig.getConsistentHashWay();
            String hashWay = "";

            RouteHashMethodEnum hashHandler = RouteHashMethodEnum.getHandler(consistentHashWay);
            hashWay = hashHandler.getClazz();
            AbstractConsistentHash consistentHash
                    = (AbstractConsistentHash) Class.forName(hashWay).newInstance();
            setHash.invoke(routeHandle,consistentHash);
        }
        return routeHandle;
    }

    @Bean
    public EasySqlInjector easySqlInjector () {
        return new EasySqlInjector();
    }

    @Bean
    public SnowflakeIdWorker buildSnowflakeSeq() throws Exception {
        return new SnowflakeIdWorker(0);
    }




}
